package utils;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class SysInToClipboard implements ClipboardOwner {
	public static void main(String[] args) {
		if (args == null || args.length == 0) {
			readFromSysIn();
		} 
		else if (args[0].equals("?")){
			System.err.println("SysIntoClipboard [-clipboardtorawtext] [-clipboardtosysout]" +
					"\n -clipboardtorawtext - converts rich text to text" +
					"\n -clipboardtosysout - writes clipboard text to sysout");
		}
		else if (args[0].equals("-clipboardtorawtext")){
			toText();
		}
		else if (args[0].equals("-clipboardtosysout")){
			System.out.println(toText());
		}
		else {
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < args.length; i++) {
				sb.append(args[i]);
				sb.append("\n");
			}
			if (sb != null && sb.toString().trim().length() > 0) {
				writeToClipboard(sb);
			}
		}

	}

	private static void readFromSysIn() {
		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(isr);
		StringBuffer sb = new StringBuffer();
		String s = null;
		String last = null;
		try {
			s = br.readLine();
			while (s != null) {
				sb.append(s);
				sb.append("\n");
				last = s;
				s = br.readLine();
			}
//			if (last != null) {
//				sb.append(last); // fast - no if's in loop
//				sb.append("\n");
//			}
		if (sb != null && sb.toString().trim().length() > 0) {
				writeToClipboard(sb);
			}
		} catch (IOException e) {
			System.err.println(e.getMessage());
			System.exit(99);
			// e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					System.err.println(e.getMessage());
					System.exit(99);
					// e.printStackTrace();
				}
			}
		}
	}

	private static void writeToClipboard(StringBuffer sb) {
		StringSelection stringSelection = new StringSelection(sb.toString());
		Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
		clipboard.setContents(stringSelection, new SysInToClipboard());
	}
	  /**
	  * Get the String residing on the clipboard.
	  *
	  * @return any text found on the Clipboard; if none found, return an
	  * empty String.
	  */
	  public static String toText() {
	    String result = "";
	    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
	    //odd: the Object param of getContents is not currently used
	    Transferable contents = clipboard.getContents(null);
	    boolean hasTransferableText =
	      (contents != null) &&
	      contents.isDataFlavorSupported(DataFlavor.stringFlavor)
	    ;
	    if ( hasTransferableText ) {
	      try {
	        result = (String)contents.getTransferData(DataFlavor.stringFlavor);
	      }
	      catch (UnsupportedFlavorException ex){
	        //highly unlikely since we are using a standard DataFlavor
	        System.out.println(ex);
	        ex.printStackTrace();
	      }
	      catch (IOException ex) {
	        System.out.println(ex);
	        ex.printStackTrace();
	      }
	    }
	    writeToClipboard(new StringBuffer(result));
	    return result;
	  }
	@Override
	public void lostOwnership(Clipboard arg0, Transferable arg1) {
		// TODO Auto-generated method stub

	}
}
